﻿using AnQinFrameWorkAPI.DataBase;
using AnQinFrameWorkAPI.Entity.BaseInfo.View.Staff;
using AnQinFrameWorkAPI.Entity.SystemCore.DTO.Login;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using FrameWork.JWT;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace AnQinFrameWorkAPI.Service.SystemCore;

/// <summary>
///     登录业务层
/// </summary>
public class LoginService
{
    #region 登录

    public async Task<RequestResponseModel> UserLogin(LoginDTO loginDTO)
    {
        var query = await _context.Staff
            .Where(s => s.Account == loginDTO.Account)
            .Select(s => new
            {
                s.Id,
                s.Account,
                s.Password,
            })
            .AsNoTracking()
            .FirstOrDefaultAsync();

        //找不到账号
        if (query == null) return RequestResponse.BadRequest("找不到该用户!", loginDTO.Account);

        //账号或者密码错误
        if (query.Password != loginDTO.Password) return RequestResponse.BadRequest("账号或者密码错误!", loginDTO.Account);

        //生成token
        var token = _tokenService.GenerateToken(query.Id.ToString());

        //返回Token
        return RequestResponse.OK(token, "登录成功");
    }

    #endregion

    #region 校验token

    public async Task<RequestResponseModel> GetUserDetail()
    {
        //查找账号
        var query = await _context.Staff
            .Where(s => s.Id.ToString() == _userContext.UserId)
            .ProjectTo<StaffView>(_mapper.ConfigurationProvider)
            .AsNoTracking()
            .FirstOrDefaultAsync();

        //返回Token
        return RequestResponse.OK(query, "验证成功");
    }

    #endregion

    #region 初始化

    //数据库
    private readonly DatabaseContext _context;

    //token生成器
    private readonly TokenService _tokenService;

    //解密token
    private readonly IUserContext _userContext;

    //autoMapper
    private readonly IMapper _mapper;

    //构造注入
    public LoginService(IUserContext userContext, DatabaseContext DatabaseContext, TokenService tokenService,
        IMapper mapper)
    {
        _userContext = userContext;
        _context = DatabaseContext;
        _tokenService = tokenService;
        _mapper = mapper;
    }

    #endregion
}